//
//  HNLoginViewController.m
//  JHFBaseProject
//
//  Created by 朱传正 on 2016/12/29.
//  Copyright © 2016年 好牛. All rights reserved.
//

#import "HNLoginViewController.h"
#import "HNRegisterController.h"
#import "HNForgetPwdController.h"
#import "ChatDemoHelper.h"

@interface HNLoginViewController (){
    NSMutableDictionary * _userInfo;
}

@end

@implementation HNLoginViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (IBAction)searchPwdAction:(UIButton *)sender {
    HNForgetPwdController *normalMsgVC = [[HNForgetPwdController alloc]init];
    [self.navigationController pushViewController:normalMsgVC animated:YES];
}


- (IBAction)loginAction:(UIButton *)sender {
    
    if (!_loginBtn.selected) {
        [self showHint:@"请阅读白大夫约束规则"];
        return;
    }
    
    if (![_username.text isMobileNumber]) {
        [self showHint:@"手机号码格式不正确"];
        return;
    }
    if (![_pwd.text isPassWord]) {
        [self showHint:@"密码长度在6~16位"];
        return;
    }
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:_username.text,@"username",_pwd.text,@"password",@"1",@"isDoctor",nil];
    NSLog(@"param = %@",param);
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_Login parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        
        NSLog(@"responseObject = %@",responseObject);
        
        NSLog(@"NSDictionary = %@",(NSDictionary *)responseObject);
        
        NSLog(@"NSArray = %@",(NSArray *)responseObject);
        
        NSLog(@"NSString = %@",(NSString *)responseObject);
        
        NSLog(@"Data = %@",(NSData *)responseObject);
        
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"登录失败"];
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            
            
            NSDictionary * obj = [NSDictionary dictionaryWithDictionary:[data objectForKey:@"obj"]];
            
            NSString *sessionId = [NSString stringWithFormat:@"%@",[obj objectForKey:@"sessionId"]];
            
            
            NSLog( @"sessionId = %@",sessionId);
            
            [AppConfig saveUserInfo:param];
            [Util addSessionId:sessionId];
            
            [self loginWithUsername:_username.text password:@"111111"];
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"登录失败"];
    }];

    
}


#pragma -mark 登录环信
//点击登陆后的操作
- (void)loginWithUsername:(NSString *)username password:(NSString *)password
{
    //当前的登录名
    
    [self showHudInView:self.view hint:nil];//NSLocalizedString(@"login.ongoing", @"Is Login...")
    //异步登陆账号
    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMError *error = [[EMClient sharedClient] loginWithUsername:username password:password];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakself hideHud];
            if (!error) {
                //设置是否自动登录
                [[EMClient sharedClient].options setIsAutoLogin:YES];
                
                //获取数据库中数据
                [self showHudInView:self.view hint:nil];
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    [[EMClient sharedClient] dataMigrationTo3];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[ChatDemoHelper shareHelper] asyncGroupFromServer];
                        [[ChatDemoHelper shareHelper] asyncConversationFromDB];
                        [[ChatDemoHelper shareHelper] asyncPushOptions];
                        [self hideHud];
                        //发送自动登陆状态通知
                        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@([[EMClient sharedClient] isLoggedIn])];
                        
                        //保存最近一次登录用户名
                        [weakself saveLastLoginUsername];
                        
                        [AppConfig saveUserInfo:_userInfo];
                        //                          [self downLoadUserInfo];
                        
                    });
                });
            } else {
                switch (error.code)
                {
                        //                    case EMErrorNotFound:
                        //                        TTAlertNoTitle(error.errorDescription);
                        //                        break;
                    case EMErrorNetworkUnavailable:
                        TTAlertNoTitle(NSLocalizedString(@"error.connectNetworkFail", @"No network connection!"));
                        break;
                    case EMErrorServerNotReachable:
                        TTAlertNoTitle(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
                        break;
                    case EMErrorUserAuthenticationFailed:
                        TTAlertNoTitle(error.errorDescription);
                        break;
                    case EMErrorServerTimeout:
                        TTAlertNoTitle(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
                        break;
                    default:
                        TTAlertNoTitle(NSLocalizedString(@"login.fail", @"Login failure"));
                        break;
                }
            }
        });
    });
    
}

#pragma  mark - private
- (void)saveLastLoginUsername
{
    NSString *username = [[EMClient sharedClient] currentUsername];
    if (username && username.length > 0) {
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud setObject:username forKey:[NSString stringWithFormat:@"em_lastLogin_username"]];
        [ud synchronize];
    }
}




- (IBAction)registerAction:(UIButton *)sender {
    HNRegisterController *normalMsgVC = [[HNRegisterController alloc]init];
    [self.navigationController pushViewController:normalMsgVC animated:YES];

}


- (IBAction)roleStateAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [_roleStateImage setHighlighted:YES];
        [_loginBtn setSelected:YES];
        _loginBtn.backgroundColor = RGB(87, 190, 76);
    }else{
        [_roleStateImage setHighlighted:NO];
        [_loginBtn setSelected:NO];
        _loginBtn.backgroundColor = [UIColor grayColor];
    }
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    _loginBtn.backgroundColor = [UIColor grayColor];
    _loginBtn.selected = NO;
    
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGColorRef color = CGColorCreate(colorSpaceRef, (CGFloat[]){226.0/255.0,226.0/255.0,226.0/255.0,1});

    
    _telView.layer.masksToBounds = YES;
    _telView.layer.cornerRadius = 1;
    _telView.layer.borderColor = color;
    _telView.layer.borderWidth = 1;
    
    _pwdView.layer.masksToBounds = YES;
    _pwdView.layer.cornerRadius = 1;
    _pwdView.layer.borderColor = color;
    _pwdView.layer.borderWidth = 1;
    
    _registerBtn.layer.masksToBounds = YES;
    _registerBtn.layer.borderColor = color;
    _registerBtn.layer.borderWidth = 1;


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
